package com.felix.thread.printabc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.felix.constant.Constant.INT_3;

/**
 * PrintAbcUsingLock
 *
 * @author xuejinhua
 * @date 2018/10/25 14:59
 */
public class PrintAbcUsingLock {

    private int time;
    private int state;
    private Lock lock = new ReentrantLock();

    public PrintAbcUsingLock(int time) {
        this.time = time;
    }


    public static void main(String[] args) {
        PrintAbcUsingLock printABC = new PrintAbcUsingLock(10);
        new Thread(printABC::printA).start();
        new Thread(printABC::printB).start();
        new Thread(printABC::printC).start();
    }

    private void printA() {
        print("a", 0);
    }

    private void printB() {
        print("b", 1);
    }

    private void printC() {
        print("c", 2);
    }

    private void print(String name, int targetState) {
        for (int i = 0; i < time; ) {
            lock.lock();
            if (state % INT_3 == targetState) {
                state++;
                i++;
                System.out.print(name);
            }
            lock.unlock();
        }
    }
}
